<template>
  <XhhTable
    ref="table"
    :columns="columns"
    :api="api"
    :form-config="formConfig"
    :params="formConfig.form"
    unique-id="user-list-table"
    is-pagination
    stripe
    checkbox
    :setEditDialog="setEditDialog"
    :row-class-name="handleRowClassName"
    :importConfig="importConfig"
    @delete="handleDelete"
    @del="handleDel"
    @disableRow="handleDisableRow"
    @enableRow="handleEnableRow"
    @export="handleExport"
  ></XhhTable>
</template>
<script setup>
import { ref } from 'vue'
import req from '@/utils/req/axios'
import { tip, tipBox } from '@tip'
import { XhhAreaSelect } from 'xhh-design'
import { phoneRule, requiredRule, emailRule } from '@/utils/common/form'
import urls from '@/utils/constants/urls.js'
import { downloadFile } from '@/utils/common/window/index.js'
import { listBySetCodeApi, showOverflowTooltip } from '@/utils/constants/utils'
import { calculateAge } from '@/utils/common/date'

const table = ref()
const genderName = ref('')
const maritalStatusName = ref('')

const columns = ref([
  {
    prop: 'userName',
    label: '姓名',
    width: 120,
  },
  {
    prop: 'genderName',
    label: '性别',
    width: 60,
  },
  {
    prop: 'birth',
    label: '生日',
    width: 100,
  },
  {
    prop: 'age',
    label: '年龄',
    width: 100,
    formatter(row) {
      return row.birth ? calculateAge(row.birth) : ''
    },
  },
  {
    prop: 'mobile',
    label: '手机',
    width: 140,
  },
  {
    prop: 'address',
    label: '地址',
    formatter(row) {
      return row.address ? `${row.address.split('/').join('')}${row.addressDetail}` : ''
    },
    ...showOverflowTooltip,
  },
  {
    prop: 'maritalStatusName',
    label: '婚姻',
    width: 120,
  },
  {
    prop: 'email',
    label: '邮箱',
    width: 220,
    ...showOverflowTooltip,
  },
  {
    prop: 'op',
    label: '操作',
    buttons({ row }) {
      return [
        'delete',
        'edit',
        'view',
        {
          // status 1 表示已启用 其他表示已停用
          prop: row.status === '1' ? 'disableRow' : 'enableRow',
          label: row.status === '1' ? '停用' : '启用',
          class: row.status === '1' ? 'red' : 'green',
        },
      ]
    },
    width: 270,
  },
])
const api = {
  async request(params) {
    const { total, data } = await req.post(urls.v1.system.user.list, {
      ...params,
      ...(params.status === undefined ? { status: '' } : {}),
    })
    return {
      total,
      data,
    }
  },
}
const birthdayRange = ref([])
const formConfig = {
  form: {
    status: '1',
  },
  schema: [
    {
      prop: 'userName',
      label: '姓名',
    },
    {
      prop: 'birthday',
      label: '出生日期',
      comp: 'ElDatePicker',
      props: {
        'popper-class': 'date-select-popper',
        type: 'daterange',
        shortcuts: [
          {
            text: '婴幼儿(0～6岁)',
            value() {
              const end = new Date()
              const start = new Date()
              start.setFullYear(start.getFullYear() - 6)
              return [start, end]
            },
          },
          {
            text: '大龄儿童(6～12岁)',
            value() {
              const end = new Date()
              const start = new Date()
              start.setFullYear(start.getFullYear() - 12)
              end.setFullYear(start.getFullYear() - 6)
              return [start, end]
            },
          },
          {
            text: '青少年(12～18岁)',
            value() {
              const end = new Date()
              const start = new Date()
              start.setFullYear(start.getFullYear() - 18)
              end.setFullYear(start.getFullYear() - 12)
              return [start, end]
            },
          },
          {
            text: '青壮年(18～60岁)',
            value() {
              const end = new Date()
              const start = new Date()
              start.setFullYear(start.getFullYear() - 60)
              end.setFullYear(start.getFullYear() - 18)
              return [start, end]
            },
          },
          {
            text: '老年(60～70岁)',
            value() {
              const end = new Date()
              const start = new Date()
              start.setFullYear(start.getFullYear() - 70)
              end.setFullYear(end.getFullYear() - 60)
              return [start, end]
            },
          },
          {
            text: '高龄(70岁以上)',
            value() {
              const end = new Date()
              const start = new Date()
              start.setFullYear(start.getFullYear() - 300)
              end.setFullYear(start.getFullYear() - 70)
              return [start, end]
            },
          },
        ],
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
    },
    {
      prop: 'status',
      label: '状态',
      comp: 'select',
      props: {
        options: [
          {
            id: '1',
            name: '启用',
          },
          {
            id: '2',
            name: '禁用',
          },
        ],
      },
    },
  ],
  queryFormProps: {},
  // 如果配置了dialogForm，则新增按钮会自动弹出
  dialogForm: {},
  dialogSchema: [
    {
      prop: 'userName',
      label: '姓名',
    },
    {
      prop: 'gender',
      label: '性别',
      comp: 'select',
      props: {
        ...listBySetCodeApi('SYS_GENDER'),
        onChangeVal(val) {
          genderName.value = val ? val.name : ''
        },
      },
    },
    {
      prop: 'birth',
      label: '生日',
      comp: 'el-date-picker',
      props: {
        defaultValue: new Date('2000-01-01'),
        'disabled-date'(date) {
          return date > Date.now()
        },
      },
    },
    {
      prop: 'mobile',
      label: '手机',
    },
    {
      prop: 'address',
      label: '地址',
      comp: XhhAreaSelect,
    },
    {
      prop: 'addressDetail',
      label: '详细地址',
    },
    {
      prop: 'maritalStatus',
      label: '婚姻',
      comp: 'select',
      props: {
        ...listBySetCodeApi('SYS_MARITAL_STATUS'),
        onChangeVal(val) {
          maritalStatusName.value = val ? val.name : ''
        },
      },
    },
    {
      prop: 'email',
      label: '邮箱',
    },
  ],
  dialogFormProps: {
    rules: {
      ...requiredRule('userName'),
      ...phoneRule('mobile'),
      ...emailRule('email'),
    },
  },
  dialogProps: {
    async onConfirm() {
      // todo 验证表单
      await table.value.validDialogForm()
      // 如果验证失败，直接就在内部抛出错误了，下边的代码不会走了
      // 获取表单数据
      // 整理表单数据
      let url
      // 发送请求
      if (table.value.dialogFormMode === 'add') {
        // 新增
        url = urls.v1.system.user.add
      } else if (table.value.dialogFormMode === 'edit') {
        // 编辑
        url = urls.v1.system.user.update
      }
      // 表单数据
      const params = {
        ...table.value.dialogForm,
        genderName: genderName.value,
        maritalStatusName: maritalStatusName.value,
      }
      await req.post(url, params)
      // 关闭弹窗
      table.value.closeFormDialog()
      // 刷新列表
      table.value.searchData(true)
    },
  },
}

const importConfig = {
  api: {
    async requestTemplate() {
      const res = await req.post(
        urls.v1.system.user.exportTemplate,
        {},
        {
          responseType: 'blob',
        },
      )
      return res.data
    },
    requestImport(formData, headers) {
      return req.post(urls.v1.system.user.import, formData, {
        headers,
        _isReturnOrigin: true,
      })
    },
  },
}

function setEditDialog({ props, scope }) {
  props.dialogForm.value = scope.row
  genderName.value = scope.row.genderName
  maritalStatusName.value = scope.row.maritalStatusName
}

/**
 * 单个删除
 * @param row
 * @returns {Promise<void>}
 */
async function handleDelete({ row }) {
  await req.post(urls.v1.system.user.del, { id: row.id })
  table.value.searchData(true)
}

/**
 * 批量删除
 * @returns {Promise<void>}
 */
async function handleDel() {
  if (!table.value.checkedRows?.length) {
    tip({ message: '请选择要删除的行', type: 'error' })
    return
  }
  await req.post(urls.v1.system.user.del, {
    ids: table.value.checkedRows.map((item) => item.id),
  })
  table.value.searchData()
}

/**
 * 导出excel
 * @returns {Promise<void>}
 */
async function handleExport() {
  const dataLength = table.value.checkedRows?.length
  // 若存在选中的数据，则导出选中的数据，否则按条件导出数据
  const confirm = await tipBox.confirm(
    dataLength ? `确认要导出选中的${dataLength}条数据吗？` : `确认要根据查询条件导出数据吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  if (confirm === 'confirm') {
    // 查询条件
    const res = await req.post(
      urls.v1.system.user.export,
      {
        ...(dataLength
          ? { ids: table.value.checkedRows.map((item) => item.id) }
          : { ...table.value.queryForm }),
      },
      { responseType: 'blob' },
    )
    // 将流转化为文件进行下载 todo 文件名称从后端获取，从headers中获取
    downloadFile({ blob: res.data, fileName: '用户列表.xlsx' })
  }
}

async function handleStatusRow({ row, status, message, label }) {
  const confirm = await tipBox.confirm(`确认要执行${label}操作吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  if (confirm === 'confirm') {
    await req.post(urls.v1.system.user.update, { id: row.id, status }, { _showSuccessTip: false })
    tip({ message, type: 'success' })
    table.value.searchData(true)
  }
}

async function handleDisableRow({ row }) {
  await handleStatusRow({ row, status: '2', message: '停用成功', label: '停用' })
}

async function handleEnableRow({ row }) {
  await handleStatusRow({ row, status: '1', message: '启用成功', label: '启用' })
}

function handleRowClassName({ row }) {
  return row.status === '1' ? 'enable-row' : 'disable-row'
}
</script>
<style lang="less">
.date-select-popper {
  .el-picker-panel__sidebar {
    width: 150px;
  }

  .el-picker-panel [slot='sidebar'] + .el-picker-panel__body,
  .el-picker-panel__sidebar + .el-picker-panel__body {
    margin-left: 150px;
  }
}
</style>
